package binarySearch;

//https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/description/
public class l_34 {
    public int[] searchRange(int[] nums, int target) {
        int[] ans = new int[]{-1, -1};
        if(nums.length == 0) return ans;
        int left = 0, right = nums.length - 1;


        //两种非朴素的二分查找
        //mid 不加 1(看 if-else 有没有-1)
        while(left < right)
        {
            int mid = left + (right - left) / 2;
            if(nums[mid] < target) left = mid + 1;
            else right = mid;
        }
        if(nums[left] != target) return ans;
        ans[0] = left;
        //这里left可以不用为0, 初始化为上一次查左端点的right即可
        left = 0; right = nums.length - 1;


        //mid 加 1(看 if-else 有没有-1)
        while(left < right)
        {
            int mid = left + (right - left + 1) / 2;
            if(nums[mid] <= target) left = mid;
            else right = mid - 1;
        }
        ans[1] = left;
        return ans;
    }
}

//模板
//while(left < right)
//{
//    int mid = left + (right - left) / 2;
//    if( ... )
//          left = mid + 1;
//    else
//          right = mid;
//}

//while(left < right)
//{
//    int mid = left + (right - left + 1) / 2;
//    if( ... )
//          left = mid;
//    else
//          right = mid - 1;
//}
